package cn.uhua.erp.pms.common.model;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import lombok.Data;

@Data
@Entity
@Table(name = "users")
public class User {
    @Id // 主键标识
    @Column(name = "username", length = 50, nullable = false)
    private String username; // 用户名（登录标识）

    @Column(name = "password", length = 500, nullable = false)
    private String password; // 加密后的密码

    @Column(name = "expire_date")
    private LocalDateTime expireDate; // 账户过期时间（NULL表示永不过期）

    @Column(name = "locked", nullable = false)
    private boolean locked = false; // 账户是否锁定，默认未锁定

    @Column(name = "credentials_expire_date")
    private LocalDateTime credentialsExpireDate; // 凭证（密码）过期时间

    @Column(name = "enabled", nullable = false)
    private boolean enabled = true; // 账户是否启用，默认启用

    @Column(name = "create_time", nullable = false, updatable = false)
    @CreationTimestamp // 自动填充创建时间
    private LocalDateTime createTime;

    @Column(name = "update_time", nullable = false)
    @UpdateTimestamp // 自动更新时间
    private LocalDateTime updateTime;

    public boolean isEnabled() {
        return enabled;
    }

    public boolean isLocked() {
        return locked;
    }

    public boolean isAccountExpired () {
        return expireDate != null && expireDate.isBefore(LocalDateTime.now());
    }

    public boolean isCredentialsExpired() {
        return credentialsExpireDate != null && credentialsExpireDate.isBefore(LocalDateTime.now());
    }

    // 关联权限集合，一对多关系
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    private Set<Authority> authorities = new HashSet<>();

}
